package com.zang.schema.strategy;

import com.zang.schema.strategy.total.*;
import org.apache.commons.configuration.XMLConfiguration;

import org.apache.commons.configuration.ConfigurationException;

/**
 * 算法工厂
 * 工厂模式创建创建对象，可通过反射、配置文件与传参直接创建
 * @author Zhang Qiang
 * @Date 2019/8/30 16:43
 */
public class StrategyFactory {

    /**
     * switch创建
     *
     * @param strategyEnum
     * @return
     */
    public static Travel createTravel(StrategyEnum strategyEnum){
        Travel travel = null;
        switch (strategyEnum.value){
            case "car":
                travel = new TravelCarTotal();
                break;
            case "train":
                travel = new TravelTrainTotal();
                break;
            case "ferryboat":
                travel = new TravelFerryBoatTotal();
                break;
            case "plane":
                travel = new TravelPlaneTotal();
                break;
            case "selfDriver":
                travel = new TravelSelfDriverTotal();
                break;
            default:
                System.out.println("未找到算法");
                return travel;
        }
        return travel;
    }

    /**
     * 反射创建
     *
     * @param strategyClassName
     * @return
     */
    public static Travel createTravelByNewInstend(StrategyClassEnum strategyClassName){
        Travel travel = null;
        try {
            travel = (Travel) Class.forName(strategyClassName.value).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return travel;
    }


    /**
     * xml创建
     *
     * @return
     */
    public static Travel createTravelByXml(){
        Travel travel = null;
        String travelName = "";
        try {
            XMLConfiguration xmlConfiguration = new XMLConfiguration("travel.xml");
            travelName = xmlConfiguration.getString("travel.name");
        } catch (ConfigurationException e) {
            e.printStackTrace();
            System.out.println("xml文件读取错误");
        }
        if ("car".equals(travelName)){
            travel = new TravelCarTotal();
        } else  if ("train".equals(travelName)){
            travel = new TravelTrainTotal();
        } else  if ("ferryboat".equals(travelName)){
            travel = new TravelFerryBoatTotal();
        } else  if ("plane".equals(travelName)){
            travel = new TravelPlaneTotal();
        } else  if ("selfDriver".equals(travelName)){
            travel = new TravelSelfDriverTotal();
        }
        return travel;
    }

}
